from django.core.mail import SMTPConnection
from django.conf import settings
import os

SENDMAIL = getattr(settings, 'SENDMAIL_PATH', "/usr/sbin/sendmail")

class LocalSendmail(SMTPConnection):
  def open(self):
    if self.connection:
      return False
    try:
      self.connection = os.popen("%s -t" % SENDMAIL, "w")
    except:
      if not self.fail_silently:
        raise

  def close(self):
    try:
      self.connection.close()
    except:
      if not self.fail_silently:
        raise
    self.connection = None

  def send_messages(self, email_messages):
    for m in email_messages:
      self.open()
      self._send(m)
      self.close()

  def _send(self, email_message):
    if not email_message.recipients():
      return False
    try:
      self.connection.write(email_message.message().as_string())
    except:
      if not self.fail_silently:
        raise
    return True

default_connection = locals()[getattr(settings, 'DEFAULT_SMTP_CONNECTION', 'SMTPConnection')]

